<?php

namespace App\Recharge\Api;

use App\Models\Admin\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use GuzzleHttp\Promise\PromiseInterface;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Pool;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class Kameng extends AbstractApi
{
    /**
     * @param array $array
     * @param string $secret_key
     * @return string
     */
    public function sign(array $array, string $secret_key): string
    {
        $str = '';
        foreach ($array as $k => $v) {
            $str .= $k . $v;
        }
        return md5($secret_key . $str);
    }

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $array = [
            'customer_id'       => $bean->getSupplierNum(), //商户号
            'notify_url'        => $bean->getNotifyUrl(), //异步回调地址
            'outer_order_id'    => $bean->getOrderNo(),
            'product_id'        => $bean->getGoodsId(), //商品编号id
            'quantity'          => $bean->getRechargeNum(), //充值数量
            'recharge_account'  => $bean->getAccount(), //要充值的用户
            'safe_cost'         => $bean->getUnitPrice(),
            'timestamp'         => time(),//时间戳
        ];
        $array['sign'] = $this->sign($array, $bean->getSecretKey());
        return $array;
    }

    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('state', '');
        $order_sn = $request->input('outer_order_id', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(in_array($status, ['200', '500']))->setRechargeSuccess($status == '200');
    }
}
